package com.woniuxy.auth.controller;

import com.woniuxy.commons.entity.User;
import com.woniuxy.commons.enums.ResultEnum;
import com.woniuxy.commons.util.JwtUtil;
import com.woniuxy.commons.util.ResponseResult;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Author: yangtao
 * @date 2021/8/5 14:30
 * @Version 1.0
 */
@RestController
@RequestMapping("/auth")
public class AuthController {
    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    @PostMapping("/login")
    public ResponseResult login(@RequestBody User user, HttpServletResponse response){
        //1、通过账号作为查询条件得到结果判断
        //2、如果比对成功，说明登陆成功
        //3、利用jwt工具类生成token，返回
        String token = JwtUtil.generateToken(user.getAccount());
        String refreshToken = UUID.randomUUID().toString();
        // 4、将token和refreshtoken放入redis
        /**
         * refreshtoken作为key，token和account作为value refreshtoken:{ 假设过期时间为30天。下次就不用登录 token: xxxxxx,
         * 设置随时过期，目的是为了放置别人伪造token account: xxxxx }
         */
        HashMap<String, Object> map = new HashMap<>();
        map.put("token",token);
        map.put("account",user.getAccount());

        redisTemplate.opsForValue().set(refreshToken,map);
        redisTemplate.expire(refreshToken,30, TimeUnit.DAYS);
        System.out.println(token);
        System.out.println(refreshToken);
        //通过响应头返回给前端
        response.setHeader("authorization",token);
        response.setHeader("refreshToken",refreshToken);
        //暴露响应头(暴露多个头用逗号隔开)
        response.setHeader("Access-Control-Expose-Headers","authorization,refreshToken");
        return null;
    }

    /**
     * 接收account。perms，通过account查询得到user全部信息
     * 然后对比是否有权限，返回结果
     */
    @GetMapping("/perms/{account}/{perms}")
    public ResponseResult existPerms(@PathVariable("account") String account,@PathVariable("perms") String perms){
        //通过account查询得到当前用户的全部权限信息
        //假设得到了当前用户的全部权限信息
        List<String> permsList = Arrays.asList(
                "goods:all",
                "goods:del",
                "goods:update"
        );
        if (permsList.contains(perms)) {
            return new ResponseResult(200, ResultEnum.PERMS_YES,"当前用户"+account+"拥有"+perms+"权限",null);
        }
        return new ResponseResult(200, ResultEnum.PERMS_NO,"当前用户"+account+"不拥有"+perms+"权限",null);
    }
}
